package com.youpingou.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.youpingou.config.Websocket;
import com.youpingou.service.OrderService;
import com.youpingou.util.PayHelper;
import com.youpingou.vo.BaseResult;
import com.youpingou.vo.OrderRequest;
import com.youpingou.vo.PayRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping
public class OrderController {
    @Autowired
    private OrderService orderService;

    //由于要获取userId，所以需要request
    @Autowired
    private HttpServletRequest request;

    @PostMapping("/orders")
    public BaseResult addOrder(@RequestBody OrderRequest orderRequest){
        //调用service
        String sn = orderService.addOrder(orderRequest,request);
        return BaseResult.ok(sn);
    }

    @Autowired
    private PayHelper payHelper;

    @PostMapping("pay")
    public BaseResult crateWxURL(@RequestBody PayRequest payRequest){
        //调用工具类生成wxurl
        String payUrl = payHelper.createPayUrl(payRequest.getSn());
        // 封装返回结果
        return BaseResult.ok(payUrl);
    }
    /**
     * 查询成功之后，一定要修改本地数据
     * @param sn
     * @return
     */
    @GetMapping("/order_status/{sn}")
    public BaseResult queryOrderStatus(@PathVariable("sn") String sn){
        Integer status = payHelper.queryOrder(sn);
        return BaseResult.ok(status);
    }

    @PostMapping("/pay/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1 获得响应内容
            String xml = IOUtils.toString(request.getInputStream(), "UTF-8");
            System.out.println(xml);
            //解析
            Map<String, String> map = WXPayUtil.xmlToMap( xml );

            // 查询成功
            if("SUCCESS".equals(map.get( "result_code" )  )){

                // 获得订单号
                String sn = map.get("out_trade_no");

                //TODO  更新订单状态
                System.out.println(sn);
                // 修改订单状态
                this.orderService.updateStatus(sn, 1);
                //向前台推送消息
                Websocket.sendMessage(sn,"1");

                //如果成功，给微信支付一个成功的响应
                response.setContentType("text/xml");
                String data = "P<![CDATA[OK]]></return_msg></xml>";
                response.getWriter().write(data);
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA["+e.getMessage()+"]]></return_msg></xml>";
            response.getWriter().write(data);
        }
    }

}